/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.tianyun.cloud.common.constants.ResponseCode;
import org.tianyun.cloud.common.dto.RestResult;
import org.tianyun.cloud.common.dto.RestResult.RestResultBuilder;
import org.tianyun.cloud.ext.i18n.I18nMessageSource;

/**
 * 控制器基类
 *
 * @auther ebert_chan
 */
public abstract class BaseController {

    @Autowired
    private I18nMessageSource messageSource;

    public I18nMessageSource getMessageSource() {
        return messageSource;
    }

    /**
     * 返回成功信息
     *
     * @return RestResult<T>
     * @auther ebert_chan
     */
    public <T> RestResult<T> success() {
        return this.success(null);
    }

    /**
     * 返回成功信息
     *
     * @param data
     * @return RestResult<T>
     * @auther ebert_chan
     */
    public <T> RestResult<T> success(T data) {
        String message = null;
        if (messageSource != null) {
            message = messageSource.getMessage(ResponseCode.SUCCESS);
        }
        return this.success(message, data);
    }

    /**
     * 返回成功信息
     *
     * @param message
     * @param data
     * @return RestResult<T>
     * @auther ebert_chan
     */
    public <T> RestResult<T> success(String message, T data) {
        RestResultBuilder<T> builder = RestResultBuilder.instance();
        builder.success(message, data);
        return builder.build();
    }

    /**
     * 返回失败信息
     *
     * @param code
     * @return RestResult<T>
     * @auther ebert_chan
     */
    public <T> RestResult<T> failure(String code) {
        return this.failure(code, null, null);
    }

    /**
     * 返回失败信息
     *
     * @param code
     * @param message
     * @return RestResult<T>
     * @auther ebert_chan
     */
    public <T> RestResult<T> failure(String code, String message) {
        return this.failure(code, message, null);
    }

    /**
     * 返回失败信息
     *
     * @param code
     * @param message
     * @param data
     * @return RestResult<T>
     * @auther ebert_chan
     */
    public <T> RestResult<T> failure(String code, String message, T data) {
        RestResultBuilder<T> builder = RestResultBuilder.instance();

        String original = null;
        if (messageSource != null) {
            original = messageSource.getMessage(code);
        }

        builder.failure(code, original != null ? original : message, data);
        return builder.build();
    }

}
